<?php
/**
* @author moufer<moufer@163.com>
* @package modoer
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');

const INTERNAL_LINK_CACHE_KEY = 'commom_internal_link_update_time';

class msm_internal_link extends ms_model {

	public $table = 'dbpre_internal_link';
	public $key    = 'id';

	public function __construct()
	{
		parent::__construct();
		$this->init_field();
	}

	public function init_field()
	{
		$this->add_field('title,url,note,target');
		$this->add_field_fun('title,url,note,target', '_T');
	}

	public function check_post($post, $keyid = FALSE)
	{
		if(!$post['title']) return $this->add_error('未填写链接标题。');
		if(!$post['url']) return $this->add_error('未填写链接地址。');
		if(!isset($post['target'])) $post['target'] = '';

		$detail = $this->db->from($this->table)->where('title', $post['title'])->get_one();
		if($detail && $keyid != $detail['id']) {
			return $this->add_error('链接标题已存在。');
		}

		return $post;
	}

    function update($post) {
        if(!$post) return;
        foreach($post as $id => $val) {
        	$data = $this->get_post($val);
            if(!parent::save($data, $id, false)) return false;
        }
        $this->write_cache();
        return true;
    }

	public function fetch_all()
	{
		$r = parent::find_all();
		if(!$r) return;

		$result = array();
		while ($v = $r->fetch_array()) {
			$result[] = $v;
		}

		return $result;
	}

	public function write_cache()
	{
		ms_cache::factory('db')->write(INTERNAL_LINK_CACHE_KEY, _G('timestamp'));
	}

	public function last_update_time()
	{
		return (int)ms_cache::factory('db')->read(INTERNAL_LINK_CACHE_KEY);
	}

}

/** end */